package jodb

import (
	"fmt"
	"github.com/pkg/errors"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"sync"
)

var (
	envDbInstance *gorm.DB
	envDbLocker   *sync.RWMutex
)

func init() {
	envDbLocker = new(sync.RWMutex)
}

func OpenDbConn(cfg *DbCfg) (*gorm.DB, error) {
	if cfg == nil {
		return nil, fmt.Errorf("config is nil")
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.User,
		cfg.Pass,
		cfg.Addr,
		cfg.Port,
		cfg.Schema)

	if db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Warn),
	}); err != nil {
		return nil, errors.Wrapf(err, "try connetct to db fail, error info: %v", err.Error())
	} else {
		return db, nil
	}
}

func RegDbConn(db *gorm.DB) {
	envDbLocker.Lock()
	defer envDbLocker.Unlock()

	envDbInstance = db
}

func GetDb() *gorm.DB {
	envDbLocker.RLock()
	defer envDbLocker.RUnlock()

	return envDbInstance
}
